package com.aiwhose.aiwhosewechatplublicaiwhose.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.aiwhose.aiwhosecore.bean.plublicaiwhose.bean.FileMediaInfoBean;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.io.File;

/**
 * @author Administrator
 */
@Component
public class WXPlubFileUtils {
    @Resource
    WXPlublicUtil wxPlublicUtil;
    @Resource
    RedisUtil redisUtil;

    public FileMediaInfoBean getFileMediaId(String fileUrl) {

        String fileUrlMD5 = MD5.create().digestHex16(fileUrl);
        Object bodyRedis = redisUtil.hget("WX_PLUCK_FILE_MEDIAID", fileUrlMD5);
        if (ObjectUtil.isNotEmpty(bodyRedis)) {
            return BeanUtil.toBean(JSONUtil.parse((String) bodyRedis), FileMediaInfoBean.class);
        }


        String accessToken = wxPlublicUtil.getAccessToken();
        // 目标API的URL，注意不包含type参数，我们稍后会根据文件类型添加
        String uploadUrl = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=" + accessToken;

        // 首先，尝试获取文件的Content-Type
        HttpResponse response = HttpUtil.createGet(fileUrl).execute();
        String contentType = response.header("Content-Type");

        // 确定文件类型
        String type;
        if (contentType != null && contentType.startsWith("image/")) {
            type = "image";
        } else if (contentType != null && (contentType.startsWith("audio/") || contentType.equals("application/octet-stream"))) {
            type = "voice"; // 假设所有音频或不明确类型均为voice
        } else if (contentType != null && contentType.startsWith("video/")) {
            type = "video";
        } else {
            // 如果无法识别类型，可以选择跳过上传或设定默认类型
            System.out.println("Unsupported file type: " + contentType);
            type = "image";
        }

        // 更新上传URL包含文件类型
        uploadUrl += "&type=" + type;

        // 下载文件到字节数组
        byte[] fileBytes = response.bodyBytes();

        // 根据下载的文件内容创建临时文件
        File tempFile = FileUtil.writeBytes(fileBytes, FileUtil.getTmpDirPath() + "/" + URLUtil.decode(fileUrl).substring(fileUrl.lastIndexOf('/') + 1));

        try {
            // 使用Hutool上传文件
            HttpResponse uploadResponse = HttpRequest.post(uploadUrl)
                    .form("media", tempFile) // 添加文件到表单
                    .execute();

            if (uploadResponse.isOk()) {
                System.out.println("Upload successful: " + uploadResponse.body());
                String body = uploadResponse.body();

                redisUtil.hset("WX_PLUCK_FILE_MEDIAID", fileUrlMD5, body, 60 * 10);

                FileMediaInfoBean bean = BeanUtil.toBean(JSONUtil.parse(body), FileMediaInfoBean.class);
                return bean;
            } else {
                System.out.println("Failed to upload file.");
                return null;
            }
        } finally {
            // 上传完成后删除临时文件
            FileUtil.del(tempFile);
        }
    }
}